<template>
  <div id="imooc-container" :ref="refName">
      <slot></slot>
  </div>
</template>

<script >
import { debounce } from "../../utils/index";
import {
  defineComponent,
  ref,
  getCurrentInstance,
  onMounted,
  onUnmounted,
  nextTick,
} from "vue";
export default defineComponent({
  name: "ImoocContainer",
  props: {
    options: Object,
  },
  setup(ctx) {
    const refName = "imooc-container";
    const width = ref(0);
    const height = ref(0);
    const originalWidth = ref(0);
    const originalHeight = ref(0);
    let context;
    let dom;
    const initSize = (resize=true) => {
      return new Promise((resolve) => {
        nextTick(() => {
          dom = context.$refs[refName];
          console.log(dom.clinetWidth)
          //获取大屏真实尺寸
          if (ctx.options && ctx.options.width && ctx.options.height) {
            width.value = ctx.options.width;
            height.value = ctx.options.height;
          } else {
            width.value = dom.clinetWidth;
            height.value = dom.clinetHeight;
          }
          //获取画布尺寸
          if (!originalWidth.value || !originalHeight.value) {
            originalWidth.value = window.screen.width;
            originalHeight.value = window.screen.height;
          }
            // if (typeof onResize === 'function' && resize) onResize()
            resolve();
        });
      });
      
    };

    const updateSite = () => {
      if (width.value && height.value) {
        dom.style.width = `${width.value}px`;
        dom.style.height = `${height.value}px`;
      }
    };

    const updateScale = () => {

       dom = context.$refs[refName];
  
      //获取真实视口尺寸
      const currentWidth = document.body.clientWidth;
      const currentHeight = document.body.clientHeight;

      //获取大屏最终宽高
      // const realWidth = width.value || originalWidth.value;
      // const realHeight = height.value || originalHeight;
      const realWidth = ctx.options.width
      const realHeight = ctx.options.height
      const widthScale = currentWidth / realWidth
      const heightScale = currentHeight / realHeight
      dom.style.transform = `scale(${widthScale}, ${heightScale})`
    };

    const onResize = async () => {
 
      await initSize();
      updateScale();
    };

    onMounted(async () => {
     
      context = getCurrentInstance().ctx;

      await initSize();
      updateSite();
      updateScale();
      window.addEventListener("resize", debounce(1000,onResize));
    });

    onUnmounted(() => {
      window.removeEventListener("resize", onResize);
    });

    return {
      refName,
    };
  },
});
</script>
<style lang="scss" scoped>
#imooc-container {
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  transform-origin: left top;
  z-index: 999;
}
</style>